<template>
  <el-card
    class="dept-energy work-bench-department__card"
    shadow="never"
    body-style="display: flex; flex-direction: column; height: calc(100% - 20px); padding: 10px 15px;"
  >
    <div class="dept-energy__header work-bench-department__card__header">
      <span class="work-bench-department__card__title dept-energy__title">能耗统计</span>
      <el-radio-group v-model="type" size="mini" @change="changeType">
        <el-radio-button label="1">日</el-radio-button>
        <el-radio-button label="2">周</el-radio-button>
        <el-radio-button label="3">月</el-radio-button>
      </el-radio-group>
    </div>
    <div class="work-bench-department__card__body dept-energy__body">
      <div class="dept-energy__item" v-for="item in active" :key="item.name">
        <div class="dept-energy__item-img-wrapper">
          <img :src="item.img" />
        </div>
        <div class="dept-energy__item-label">{{ item.label }}</div>
        <div class="dept-energy__item-value-wrapper">
          <span class="dept-energy__item-value">{{ item.value }}</span>
          <span class="dept-energy__item-unit">{{ item.unit }}</span>
        </div>
      </div>
    </div>
  </el-card>
</template>

<script>
// ============================== 导入依赖 ============================== //

import CORE from '@/CORE'
import dashboardDeptApi from '@admin/views/Workbench/WorkbenchDepartment/api'

const getImg = (name) => CORE.common(`energy/${name}.png`)

// ============================== 导出组件 ============================== //

export default {
  /**
   * 名称定义 (实际使用名称)
   */
  name: 'DeptEnergy',

  props: {
    /**
     * 部门ID
     */
    organId: { type: String, default: '' },
  },

  data() {
    return {
      list: [],
      active: [],
      /**
       * @description 时间类型
       * -1日
       * -2周
       * -3月 默认1日
       */
      type: '1',
    }
  },

  methods: {
    /**
     * @function 能耗统计
     * @param {String} organId -部门ID
     */
    queryDeptEnergyPie(organId) {
      if (!organId) return

      dashboardDeptApi.queryDeptEnergyPie({ type: 1, organId }).then((res) => {
        this.list = res.info || []
        const first = this.list[0] || {}
        const firstHead = (first.head || [])[0] || {}
        this.type = firstHead.name
        this.changeType(this.type)
      })
    },

    /**
     * @function 改变时间类型
     * @param {String} type
     */
    changeType(type) {
      this.active = this.list.filter((item) => { return item.head[0].name === type })[0].info.map((item) => {
        return {
          ...item,
          img: {
            electric: getImg('icon-elec'),
            gas: getImg('icon-gas'),
            water: getImg('icon-water'),
          }[item.name],
        }
      })
    },
  },

  mounted() {
    this.queryDeptEnergyPie(this.organId)
  },

  watch: {
    organId(newVal) {
      this.queryDeptEnergyPie(newVal)
    },
  },
}
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
